package com.ss.mq.pattern.routing;

import com.rabbitmq.client.*;
import com.ss.mq.util.RabbitUtils;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author 叁昇
 * @create 2020-12-13-21:53
 */
public class RoutingConsumer {
    public static void main(String[] args) throws Exception {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        // 匹配交换机
        channel.exchangeDeclare("direct_log", BuiltinExchangeType.DIRECT);

        // 自动生成队列名
        String queue = channel.queueDeclare().getQueue();

        System.out.print("输入接收的日志级别, 多个级别用空格隔开: ");
        String[] levelString = new Scanner(System.in).nextLine().split("\\s");

        // 遍历接收的字符串, 进行队列的绑定
        for (String level: levelString) {
            channel.queueBind(queue, "direct_log", level);
        }

        System.out.println("等待接收信息...");

        DeliverCallback deliver = (s, delivery) -> {
            String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
            String routingKey = delivery.getEnvelope().getRoutingKey();
            System.out.println("收到: [ " + routingKey + " - " + msg + " ]");
        };

        CancelCallback cancel = s -> {};

        channel.basicConsume(queue, true, deliver, cancel);
    }
}
